from fastapi import FastAPI
from pydantic import BaseModel
from tools.tools import CampusServiceTools
from smolagents import CodeAgent, LiteLLMModel
import os
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Dict

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],  # 可根据需要调整
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

import os
from smolagents import OpenAIServerModel, CodeAgent

model = OpenAIServerModel(
    model_id="gpt-4o-mini",
    api_base="https://models.inference.ai.azure.com/",
    api_key=os.environ["GITHUB_TOKEN"],
)

# model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", api_key=os.getenv("YOUR_ANTHROPIC_API_KEY"))
agent = CodeAgent(
    tools=[
        CampusServiceTools.life_service,
        CampusServiceTools.medical_service,
        CampusServiceTools.transport_service,
        CampusServiceTools.service_orgs,
        CampusServiceTools.school_news,
        CampusServiceTools.school_profile,
        CampusServiceTools.president_message,
        CampusServiceTools.academic_events,
        CampusServiceTools.school_song,
    ],
    model=model,
    add_base_tools=True,
)

campus_tools = CampusServiceTools()


class ChatRequest(BaseModel):
    message: str
    history: List[Dict[str, str]] = []  # 新增对话历史字段


@app.post("/chat")
async def chat(req: ChatRequest):
    # 只保留最近2轮对话
    short_history = req.history[-4:] if len(req.history) > 4 else req.history
    context = ""
    for turn in short_history:
        context += f"{'用户' if turn['role']=='user' else '助手'}：{turn['content']}\n"
    # 拼接当前问题
    prompt = f"{context}用户：{req.message}\n请结合上下文，只返回与当前主题最相关的信息。"
    reply = agent.run(prompt)
    new_history = req.history + [
        {"role": "user", "content": req.message},
        {"role": "assistant", "content": reply},
    ]
    return {"reply": reply, "history": new_history}